{% extends 'base.html' %}


{% block title %}
Artifical Intelligence Assistant(AIA) Chats
{% endblock %}

{% block headblock %}
<h1>Artifical Intelligence Assistant (AIA) Chats</h1>
<h2 class="alt">Chats History</h2>
{% endblock %}

{% block contents %}
    <input id="currentclskey" name="currentclskey" type="hidden" value="" />
    <input id="lastmsgkey" name="lastmsgkey" type="hidden" value="" />

    <div id="contents" class="body" style="height: 500px; overflow-y: scroll;">
    {% include "chat_items.html" %}
    </div>

    {% ifequal url_linktext 'Login' %}
    <strong>Please <a href="{{ url }}"><strong>{{ url_linktext }}</strong></a> to chat with your own private assistant!</strong>
    {% endifequal %}

    {% ifnotequal url_linktext 'Login' %}
    <!--
    <image src="/media/images/icon/icon14.jpg" width="20" height="20"/>
    -->
    <strong>Hi <font color="blue">{{ user.nickname }}</font>, I am your personal assistant. Can I help you?<strong>
    {% endifnotequal %}

    <form>
        <textarea style="height:100px; width:577px" name="message" id="message" rows="4"></textarea>
    </form>
    <strong>Tip: Press <font color="red">Enter</font> to submit, <font color="blue">SHIFT+ENTER</font> to make a new line. Just like Google Talk.<strong>
    

{% endblock %}



{% block login %}
    <a href="{{ url }}">{{ url_linktext }}</a>
{% endblock %}


{% block userdefinedblock %}
    <div class="body">
    <h3>Classification</h3>
    <div id="classlist">
    {% for cls in clss %}
    {% include "class_item.html" %}
    {% endfor %}
    </div>

    <form>
    name:<input id="addclassname" name="name" type="text" value="" /><br/>
    color:<input id="addclassiconcolor" name="iconcolor" type="text" value="#fffa7a" /><br/>
    <input id="addclassbutton" type="button" title="ADD" value="ADD" />
    </form>

    </div>
    
    <div class="body">
    <h3>Users of AIA</h3>
    {% for usr in usrs %}
    {{ usr.user.nickname }} {{ usr.access_count }} 
    <span>
    <span class="localdatetime">{{ usr.last_update|date:"Y-m-d H:i:s" }}</span>
    <input class="localdatetimevalue" type="hidden" value='{{ usr.last_update|date:"Y,m,d,H,i,s" }}' />
    </span>
    <br/>
    {% endfor %}
    </div>
{% endblock %}



{% block script %}
    <script type="text/javascript">
        
        function scrollContentsToBottom(){
            //alert($("#contents").is("div"));
            //alert($("#contents").attr("scrollHeight"));
            
            //alert("scrollTop: "+$("#contents").scrollTop);
            //alert("scrollHeight: "+$("#contents").scrollHeight);
            
            //alert("scrollTop: "+$("#contents").attr("scrollTop"));
            //alert("scrollHeight: "+$("#contents").attr("scrollHeight"));
            //var scrollHeight = $("#contents").scrollHeight();
            var scrollHeight = document.getElementById("contents").scrollHeight;
            //alert(scrollHeight);
            document.getElementById("contents").scrollTop = scrollHeight;
            //$("#contents").scrollTop(scrollHeight);
        }
        
        function addClassMenuEvent(classmenuitems){
            var classmenu =  $("#classlist").clone();
            classmenu.unbind();
            classmenu.attr("id", "justchangeit");
            
            classmenu.find(".classmenuitem").click( function(event){
                //alert("msgkey:"+ classmenuitems.siblings("#msgkey").val()+", clskey:"+$(this).find("#clskey").val());
                $.post( "/chat/mark/",
                    { msgkey: classmenuitems.siblings("#msgkey").val(), clskey: $(this).find("#clskey").val(), email: "anonymous@gmail.com" },
                    function(data){
                        if(data.indexOf("error!")==0) {
                            var errorMsgIndex = data.indexOf("!")+1;
                            var errorMsg = data.substring(errorMsgIndex);
                            alert(errorMsg);
                        } else {
                            //alert(data);
                            var datas = data.split(",");
                            var msgkey = datas[0];
                            var titlecolor = datas[1];
                            $("#title_"+msgkey).css("background", titlecolor);
                        }
                    }
                );
            });

            classmenuitems.empty();
            classmenuitems.append(classmenu);
        }
        
        function addChatContentEvent(){
            $(".chatcontent").dblclick( function (event){
                var msg = $(this).html();
                //alert(msg)
                //$("#message").val(msg);
                msg = msg.replace(/ /gi, "")
                msg = msg.replace(/\n/gi, "")
                msg = msg.replace(/<br\/>/gi, "\n")
                msg = msg.replace(/<br>/gi, "\n")
                msg = msg.replace(/&amp;/gi, "&")
                msg = msg.replace(/&gt;/gi, ">")
                msg = msg.replace(/&lt;/gi, "<")
                msg = msg.replace(/&nbsp;/gi, " ")
                //$("#message").val($("#message").val()+"\n------\n"+msg);
                
                var html = "<textarea class='chatedittextarea'>"+msg+"</textarea>";
                var edittextarea = $(html);
                $(this).empty();
                $(this).append(edittextarea);
                edittextarea.focus();
                
                $(this).unbind();
                addEditEvent(edittextarea);
            });
            
            //$(".chatcontent").mouseover( function (event){});
        }
        
        function chatEditEventFunction(event){
            if( event.type == "blur" || (event.type="keypress" &&event.keyCode == 13 && !event.shiftKey)){
                var msg = $(this).val();
                var msgkey = $(this).parent().siblings(".classmenu").find("#msgkey").val();
                $(this).parent().attr("id", "textarea_"+msgkey);
                
                //alert(msgkey+", "+msg);
                //$("#message").val(msgkey+","+msg);
                $.post( "/chat/edit/",
                    { msgkey: msgkey, message: msg, email: "anonymous@gmail.com" },
                    function(data){
                        if(data!=""){
                            if(data.indexOf("error!")==0) {
                                var errorMsgIndex = data.indexOf("!")+1;
                                var errorMsg = data.substring(errorMsgIndex);
                                alert(errorMsg);
                            } else {
                                //alert(data);
                                //$("#message").val($("#message").val()+"\ndata:"+data);
                                var commaindex = data.indexOf(",");
                                //alert(commaindex);
                                var msgkey = data.substring(0, commaindex);
                                //alert(msgkey);
                                var msg = data.substring(commaindex+1);
                                //alert(msg);
                                $("#textarea_"+msgkey).html(msg);
                            }
                        }
                    }
                );
                //$("#message").val(msg);
                msg = msg.replace(/&/g, "&amp;")
                msg = msg.replace(/>/g, "&gt;")
                msg = msg.replace(/</g, "&lt;")
                msg = msg.replace(/\n/g, "<br/>")
                msg = msg.replace(/ /g, "&nbsp;")
                //alert(msg)
                //$("#message").val($("#message").val()+"\n\n"+msg);
                
                $(this).parent().html(msg);
                
                addChatContentEvent();
                
            }
        }
        
        function addEditEvent(edittextarea){
            //edittextarea = edittextarea.find(".chatedittextarea");
            edittextarea.unbind();
            edittextarea.blur(chatEditEventFunction);
            edittextarea.keypress(chatEditEventFunction);
        }
        
        function addChatEvent(){
            //alert("aaaaaaa");
            $(".chattitlemenu").unbind();
            $(".chattitlemenu").click( function(event){
                //alert("xxxxxx");
                var classmenu = $(this).parent().siblings(".classmenu");
                var classmenuitems = classmenu.find("#classmenuitems");
                
                var display = classmenu.css("display")=="none"? "block":"none";
                classmenu.css("display", display);
                
                if(display == "block"){
                    addClassMenuEvent(classmenuitems);
                    $(this).find(".menuitemarrow").html("&#9660;");
                }else{
                    $(this).find(".menuitemarrow").html("&#9658;");
                }
            });
            //alert("bbbb");
            addChatContentEvent();
            //alert("ccccc");
        }

        function updatelastchatkey(){
            var lastmsgkey = $(".classmenu:last #msgkey");
            if(lastmsgkey.val()) {
                $("#lastmsgkey").val(lastmsgkey.val());
            } else {
                $("#lastmsgkey").val("None");
            }
            //$("#message").val("lastmsgkey: "+$("#lastmsgkey").val());
        }

        function getLocalDate(dtString){
            var dts = dtString.split(",");
            y = dts[0];
            M = dts[1];
            d = dts[2];
            h = dts[3];
            m = dts[4];
            s = dts[5];
            
            var time = Date.UTC(y, M-1, d, h, m, s);
            var date = new Date();
            date.setTime(time);
            return date.toLocaleString();
            //alert(date.toLocaleString());
        }
               
        function toLocalDateTime(){
            /*
            $(".localdatetime").each(function(i){
                var localdatetimevalue = $(this).siblings(".localdatetimevalue").val();
                //getLocalDate(localdatetimevalue);
                $(this).html("["+getLocalDate(localdatetimevalue)+"]")
            });
            */
        }
        
        function init(){
            toLocalDateTime();
            scrollContentsToBottom();
            $("#message").focus();
            addChatEvent();
            updatelastchatkey();
        }
    </script>
    
    <script type="text/javascript">
        $(document).ready(function() {
            
            init();
            
            $("#message").keypress( function(event){
                if(event.keyCode == 13 && !event.shiftKey){
                    //alert(encodeURIComponent($(this).val()));
                    $.post( "/chat/add/",
                        { message: $(this).val(), email: "anonymous@gmail.com" },
                        function(data){
                            $("#contents").append($(data));
                            scrollContentsToBottom();
                            $("#message").val("");
                            addChatEvent();
                            updatelastchatkey();
                        }
                    );
                }
            });
            
            var chatupdateevent = function() {
                //$("#message").val($("#message").val()+"\nmsgkey 1:"+$("#lastmsgkey").val());
                
                $.post( "/chat/update/",
                    { msgkey: $("#lastmsgkey").val(), clskey: $("#currentclskey").val(), email: "anonymous@gmail.com" },
                    function(data){
                        if(data!=""){
                            //alert(data);
                            //$("#message").val($("#message").val()+"\ndata:"+data);
                            $("#contents").append($(data));
                            toLocalDateTime();
                            scrollContentsToBottom();
                            addChatEvent();
                            updatelastchatkey();
                        }
                        
                        $("#contents").oneTime('5s', 'chatupdate', chatupdateevent, 0, true);
                    }
                );
                
                $("#contents").stopTime('chatupdate');
            };
            
            $("#contents").oneTime('5s', 'chatupdate', chatupdateevent, 0, true);
            

            $("#addclassbutton").click( function(event){
                $.post( "/chat/addclass/",
                    { name: $("#addclassname").val(), iconcolor: $("#addclassiconcolor").val(), email: "anonymous@gmail.com" },
                    function(data){
                        if(data.indexOf("error!")==0) {
                            var errorMsgIndex = data.indexOf("!")+1;
                            var errorMsg = data.substring(errorMsgIndex);
                            alert(errorMsg);
                        } else {
                            //alert(data)
                            //alert($("#classlist").html());
                            $("#classlist").append($(data));
                        }
                    }
                );
            });
            
            $("#classlist .classmenuitem").click( function(event){
                //alert("load: "+$(this).find("#clskey").val());
                /*
                $("#contents").load( "/chat/update/", { msgkey : "None", clskey : $(this).find("#clskey").val() }, 
                    function() {
                        $("#contents").attr("scrollTop", $("#contents").attr("scrollHeight"));
                        addChatEvent();
                        updatelastchatkey();
                    }
                );
                */
                //window.location.href="/chat/class/"+$(this).find("#clskey").val();
                //$.jqURL.loc( "/chat/classlist/"+$(this).find("#clskey").val() );
                clskey_value = $(this).find("#clskey").val();
                $("#currentclskey").val(clskey_value);
                $.post( "/chat/update/",
                    { msgkey : "None", clskey : clskey_value, email: "anonymous@gmail.com" },
                    function(data){
                        //alert(data);
                        //$("#message").val($("#message").val()+"\ndata:"+data);
                        $("#contents").html(data);
                        toLocalDateTime();
                        scrollContentsToBottom();
                        addChatEvent();
                        updatelastchatkey();
                    }
                );
            });
        
        });
    </script>
    
    <script type="text/javascript">
        
    </script>
{% endblock %}

